package guestbook;

import com.google.appengine.api.capabilities.CapabilitiesService;
import com.google.appengine.api.capabilities.CapabilitiesServiceFactory;
import com.google.appengine.api.capabilities.Capability;
import com.google.appengine.api.capabilities.CapabilityStatus;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.appengine.api.utils.SystemProperty;
import com.google.appengine.api.xmpp.JID;
import com.google.appengine.api.xmpp.MessageBuilder;
import com.google.appengine.api.xmpp.MessageType;
import com.google.appengine.api.xmpp.SendResponse;
import com.google.appengine.api.xmpp.XMPPService;
import com.google.appengine.api.xmpp.XMPPServiceFactory;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.logging.Logger;

public class SignGuestbookServlet extends HttpServlet {
    private static final Logger LOG = Logger.getLogger(SignGuestbookServlet.class.getName());

    public void doPost(HttpServletRequest req, HttpServletResponse resp)
                throws IOException {
        UserService userService = UserServiceFactory.getUserService();
        User user = userService.getCurrentUser();

        String content = req.getParameter("content");
        Date date = new Date();
        Greeting greeting = new Greeting(user, content, date);

        PersistenceManager pm = PMF.get().getPersistenceManager();
        try {
            pm.makePersistent(greeting);
        } finally {
            pm.close();
        }

        CapabilitiesService service = CapabilitiesServiceFactory.getCapabilitiesService();
        CapabilityStatus status = service.getStatus(Capability.XMPP).getStatus();
        LOG.info("xmpp disabled: " + (status == CapabilityStatus.DISABLED));

        final XMPPService xmppService = XMPPServiceFactory.getXMPPService();

        if (user != null) {
            LOG.info("usuario logueado: " + user.getEmail());
            final JID jid = new JID(user.getEmail());
            if (xmppService.getPresence(jid).isAvailable()) {
                LOG.info("usuario disponible");
                final MessageBuilder messageBuilder = new MessageBuilder();
                messageBuilder.withMessageType(MessageType.CHAT)
                        .withBody("Hola mundo. Posteaste: " + content)
                        .withRecipientJids(jid)
                        .withFromJid(new JID("researchfdv@appspot.com"));
                SendResponse response = xmppService.sendMessage(messageBuilder.build());
                boolean messageSent = (response.getStatusMap().get(jid) == SendResponse.Status.SUCCESS);
                req.getSession(true).setAttribute("messageSent", messageSent);
                LOG.info("mensaje enviado success: " + (response.getStatusMap().get(jid) == SendResponse.Status.SUCCESS));
            }
        }

        switch (SystemProperty.environment.value()) {
            case Production:
                LOG.info("In development environment");
                break;
            case Development:
                LOG.info("In production environment");
                break;
        }

        resp.sendRedirect("/guestbook.jsp");
    }
}
